using UnityEngine;
using UnityEngine.UI;

/// <summary>
/// 帧动画
/// </summary>
[RequireComponent(typeof(Image))]
public class FrameAnim : MonoBehaviour
{
    public Sprite[] spriteFrame;
    //帧动画间隔事件
    public float duration;
    //循环播放
    public bool Loop = false;
    //加载事件播放
    public bool PlayOnLoad = false;

    private float playedTime;
    private bool isPlaying;

    private Image img;
    void Start()
    {
        this.img = this.GetComponent<Image>();
        if (this.PlayOnLoad)
        {
            if (Loop)
                PlayLoop();
            else
                PlayOnce();
        }
    }

    public void PlayOnce(float speed = 0.02f)
    {
        if (spriteFrame.Length <= 1)
            return;

        duration = speed;
        playedTime = 0;
        isPlaying = true;
        Loop = false;
    }

    public void PlayLoop()
    {
        if (spriteFrame.Length <= 1)
        {
            return;
        }
        playedTime = 0;
        isPlaying = true;
        Loop = true;
    }

    public void StopAnim()
    {
        isPlaying = false;
    }
    
    void Update()
    {
        if (isPlaying == false) return;

        float dt = Time.deltaTime;
        playedTime += dt;
        int index = (int)(playedTime / duration);
        if (Loop == false)
        {
            if (index >= spriteFrame.Length)
            {
                isPlaying = false;
                playedTime = 0;
            }
            else
            {
                img.sprite = spriteFrame[index];
            }
        }
        else
        {
            while (index >= spriteFrame.Length)
            {
                playedTime -= (duration * spriteFrame.Length);
                index -= spriteFrame.Length;
            }
            img.sprite = this.spriteFrame[index];
        }
    }
}
